package com.example.cachedemo;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 转码相关的工具，比如MD5
 */
public final class EncodeUtil {
    /**
     * 将url字符串转换为MD5字符串
     * @param urlString
     * @return
     */
    public static String urlStringToMd5String(String urlString) {
        String md5String;
        try {
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(urlString.getBytes());
            md5String = EncodeUtil.bytesToHexString(digest.digest());
        } catch (NoSuchAlgorithmException e){
            md5String = String.valueOf(urlString.hashCode());
        }
        return md5String;
    }

    /**
     * byte转16进制字符串
     * @param bytes 字节数组
     * @return  16进制字符串
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
